package com.zc.timedown.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zc.common.utils.DateUtils;
import com.zc.framework.web.service.TokenService;

import com.zc.timedown.dto.UserLoginRequestDto;
import com.zc.timedown.domain.User;
import com.zc.timedown.mapper.UserMapper;
import com.zc.timedown.service.ApiUserService;
import com.zc.timedown.service.ApiWechatService;
import com.zc.timedown.utils.WeChatUserLifeCalculator;
import com.zc.timedown.vo.LifeSpanStatisticsVo;
import com.zc.timedown.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:UserServiceImpl
 * Description:
 * DateTime: 2025/9/22 10:31
 * Author: zc
 * Version: 1.0
 */
@Component
@Slf4j
public class ApiUserServiceImpl extends ServiceImpl<UserMapper, User> implements ApiUserService {
    @Autowired
    private ApiWechatService wechatService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenService tokenService;



    /**
     * 小程序端登录
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.调用微信api,根据code获取openId
        String openId = wechatService.getOpenid(userLoginRequestDto.getCode());
        //2.根据openId查询用户
        User user = getOne(Wrappers.<User>lambdaQuery(User.class)
                .eq(User::getOpenId, openId));
        //3.如果用户为空，则新增
        if (ObjectUtil.isEmpty(user)) {
            user = new User();
            user.setCreateTime(DateUtils.getNowDate());
            if (ObjectUtil.isNotEmpty(userLoginRequestDto.getNickName())){
                user.setNickName(userLoginRequestDto.getNickName());
            }
            if (ObjectUtil.isNotEmpty(userLoginRequestDto.getAvatar())) {
                user.setAvatar(userLoginRequestDto.getAvatar());
            }
        }

        user.setOpenId(openId);
        log.info("------------------------user:{}", JSON.toJSONString(user));

        String phone = "";
        //4.调用微信api获取用户绑定的手机号
        if (ObjectUtil.isNotEmpty(userLoginRequestDto.getPhoneCode())){
            phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        }

        if (user.getLoginCount() == null){
            user.setLoginCount(1);
        }else {
            user.setLoginCount(user.getLoginCount() + 1);
        }

        if (ObjectUtil.isNotEmpty(user)){
            //5.保存或修改用户
            saveOrUpdateFamilyMember(user, phone);
        }

        //6.将用户id存入token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        if (user.getNickName() != null){
            claims.put("userName", user.getNickName());
        }

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        if (user.getNickName() != null){
            loginVo.setNickName(user.getNickName());
        }
        log.info("------------------------token:{}", token);
        return loginVo;
    }

    @Override
    public User getUserInfo(Long userId) {
        return getById(userId);
    }

    @Override
    public int updateUserInfo(User user) {



        int row = userMapper.updateUser(user);
        return row;
    }

    @Override
    public LifeSpanStatisticsVo getLifeSpanStatistics(Long userId) {
        User user = getById(userId);
        if (user.getBirthDate() == null  || user.getExpectedLifespan() <= 0){
            throw new RuntimeException("请先完善用户信息");
        }
        WeChatUserLifeCalculator calculator = new WeChatUserLifeCalculator();
        LifeSpanStatisticsVo lifeSpanStatisticsVo = calculator.calculateLifeSpanStatistics(user.getBirthDate(), user.getExpectedLifespan());
        log.info(lifeSpanStatisticsVo.toString());
        return lifeSpanStatisticsVo;
    }


    /**
     * 保存或修改客户
     * @param user
     * @param phone
     */
    private void saveOrUpdateFamilyMember(User user, String phone) {

        //1.判断取到的手机号与数据库中保存的手机号不一样
//        if(ObjectUtil.notEqual(phone, user.getPhone())){
//            //设置手机号
//            user.setPhone(phone);
//        }
        //2.判断id存在
        if (ObjectUtil.isNotEmpty(user.getId())) {
            updateById(user);
            return;
        }
        //3.保存新的用户

        save(user);
    }
}
